﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace HigLabo.Net.WindowsLive
{
    /// <summary>
    /// 
    /// </summary>
    public class PostFileCommand : WindowsLiveCommand
    {
        private String _Boundary = Guid.NewGuid().ToString();
        private String _FolderID = "";
        private String _FileName = "";
        private String _ContentType = "";
        private Byte[] _FileData = null;
        /// <summary>
        /// 
        /// </summary>
        public override HttpMethodName MethodName
        {
            get
            {
                return HttpMethodName.Post;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public override string GraphApiPath
        {
            get
            {
                return _FolderID + "/files";
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="folderID"></param>
        /// <param name="fileName"></param>
        /// <param name="contentType"></param>
        /// <param name="fileData"></param>
        public PostFileCommand(String folderID, String fileName, String contentType, Byte[] fileData)
        {
            this._FolderID = folderID;
            this._FileName = fileName;
            this._ContentType = contentType;
            this._FileData = fileData;

            this.ContentType = "multipart/form-data; boundary=" + _Boundary;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        protected override byte[] SetData()
        {
            var l = new List<byte>();
            var sb = new StringBuilder(256);
            sb.Append("--");
            sb.AppendLine(_Boundary);
            sb.AppendFormat("Content-Disposition: file; filename=\"{0}\"", this._FileName);
            sb.AppendLine();
            sb.AppendLine("Content-Type: " + this._ContentType);
            sb.AppendLine();
            l.AddRange(Encoding.UTF8.GetBytes(sb.ToString()));
            l.AddRange(this._FileData);

            sb = new StringBuilder(256);
            sb.AppendFormat("--{0}--", _Boundary);
            sb.AppendLine();
            l.AddRange(Encoding.UTF8.GetBytes(sb.ToString()));

            return l.ToArray();
        }
    }
}
